package com.azh.server.datam;

import com.azh.server.datam.dataItem.DataItem;
import com.azh.server.datam.logger.Logger;
import com.azh.server.datam.page.PageMeta;
import com.azh.server.datam.pagecache.PageCache;
import com.azh.server.tx.TxManager;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-04-26
 */
public interface DataManager {

    public DataItem read(long uid) throws Exception;

    public long insert(long txId, byte[] data) throws Exception;

    public void close();

    /**
     * 从新文件创建，则需要先写pageOne
     * @param path
     * @param mem
     * @param tx
     * @return
     */
    public static DataManager create(String path, long mem, TxManager tx) {
        PageCache pageCache = PageCache.create(path, mem);
        Logger logger = Logger.create(path);
        DataManagerImpl dmi = new DataManagerImpl(pageCache, logger, tx);
        dmi.initPageMeta();
        return dmi;
    }

    /**
     * 从已有文件创建，则需要先比较第一页的校验码，查看是否要执行恢复数据流程
     * @param path
     * @param mem
     * @param tx
     * @return
     */
    public static DataManager open(String path, long mem, TxManager tx) {
        PageCache pageCache = PageCache.open(path, mem);
        Logger logger = Logger.open(path);
        DataManagerImpl dmi = new DataManagerImpl(pageCache, logger, tx);
        if (!dmi.loadCheckPageMeta()) {
            // 需要恢复数据
            Recover.recover(tx, logger, pageCache);
        }
        dmi.fillPageIndex();
        PageMeta.setVcOpen(dmi.getPageOne());
        dmi.getPageCache().flushPage(dmi.getPageOne());
        return dmi;
    }


}
